<?php

class Controller {

	private $templateVariables = array();
	private $layout = '';
	private $child = '';

	public function __construct($child) {
		$this->assign('title', '古道倦马');
		$this->layout('layout');
		$this->child = $child;
	}

	public function layout($layout) {
		$path = ROOT . '/templates/' . $layout . '.php';

		if (!file_exists($path)) {
			throw new Exception('layout not exsits.');
		}

		$this->layout = $path;
	}

	public function assign($key, $value) {
		$this->templateVariables[$key] = $value;
	}

	public function rend($template) {
		$template = ROOT . '/templates/' . strtolower(substr($this->child, 0, -10)) . '/' . $template . '.php';

		if (!file_exists($template)) {
			throw new Exception($template . 'template not exsits.');
			exit('template ' . $template . ' not exists');
		}

		if (empty($this->templateVariables)) {
			require_once($this->layout);
		} else {
			extract($this->templateVariables);

			require_once($this->layout);

			foreach (array_keys($this->templateVariables) as $key) {
				unset($$key);
			}
		}

		unset($template);
	}

	protected function json($status, $message = '', $data = array()) {
		header('Content-Type: application/json;charset=utf-8;');

		echo json_encode(array(
			'status' => $status,
			'message' => $message,
			'data' => $data
		));

		exit(0);
	}

	public function __destroy() {

	}

}